package com.example.myblog.controller;

import com.example.myblog.model.Settings;
import com.example.myblog.service.OssService;
import com.example.myblog.service.SettingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * 网站设置控制器
 */
@Controller
@RequestMapping("/admin/settings")
public class SettingsController {

    @Autowired
    private SettingsService settingsService;

    // 注入阿里云文件上传服务
    @Autowired
    private OssService ossService;

    /**
     * 显示网站设置页面
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping
    public String showSettings(Model model) {
        // 获取背景图片设置
        String backgroundImage = settingsService.getSettingValueByKey("background_image", "");
        model.addAttribute("backgroundImage", backgroundImage);
        
        return "admin/settings";
    }

    /**
     * [修改后] 保存网站设置
     * 现在接收一个文件(MultipartFile)而不是URL字符串
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public String saveSettings(
            @RequestParam(value = "backgroundImageFile", required = false) MultipartFile backgroundImageFile,
            @RequestParam(value = "currentImageUrl", required = false) String currentImageUrl,
            RedirectAttributes redirectAttributes) {
        
        try {
            String backgroundImageUrl = currentImageUrl; // 默认使用旧的URL

            // 如果上传了新文件，则进行上传操作
            if (backgroundImageFile != null && !backgroundImageFile.isEmpty()) {
                // 调用OssService上传文件并获取返回的URL
                backgroundImageUrl = ossService.uploadFile(backgroundImageFile);
            }
            
            // 保存背景图片设置
            settingsService.saveSetting("background_image", backgroundImageUrl, "首页背景图片URL");
            
            redirectAttributes.addFlashAttribute("message", "设置保存成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "设置保存失败：" + e.getMessage());
        }
        
        return "redirect:/admin/settings";
    }
}